import { defineStore } from 'pinia'
import { Names } from '../store-namespace/index'


type Result = {
  name: string
  isChu: boolean
}

/**
 * 用户登录 action 异步举例
 * @returns 
 */
const Login = (): Promise<Result> => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        name: '小满',
        isChu: true
      })
    }, 3000)
  })
}

export const useStore = defineStore(Names.Test, {
  // state 接收一个无参匿名函数，return 中写 state 中的属性
  state: () => {
    return {
      currentNum: 100,
      sname: '小明',
      useInfo: <Result>{},
    }
  },
  // 类似于 computed 计算属性，具有缓存功能
  getters: {
    getSnameGetter: (state) => {
      return `$-${state.sname}`
    }
  },
  // 支持同步和异步方法
  actions: {
    setCurrentNum(num: string) {
      console.log('[setCurrentNum] num = ', num)
      this.currentNum++;
    },
    async login() {
      const ret = await Login()
      this.useInfo = ret
      // actions 之间相互调用
      console.log('this.getUserName(); = ', this.getSname())
    },
    getSname() {
      return this.sname
    }
  }
})
